/*
 * Protocol.h
 *
 *  Created on: 2012. 5. 8.
 *      Author: yjpark
 */

#ifndef PROTOCOL_H_
#define PROTOCOL_H_

/*
 * for HEADER
 *  0  2  4  6  8  10 12 14 16 18 20 22 24 26 28 30
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 * | Protocol                                |
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 * | Message Type                            |
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 * | Length                                  |
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *
 * for DATA
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 * | Data(Encode: Binary-Log, Text-Calculate)|
 * | ...                                           |
 * +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 */
struct CalcInfo {
	int protocol; // 4 bytes
	int messageType; // 4 bytes
	int length; // 4 bytes, 0 or numeric(only if DATA encoded by Binary)
};

// Protocol
enum {
	PROTOCOL_NM = 0xABCDEF00
};

// Message Type
enum {
	M_HELLO = 0x01, // 접속 시작
	M_BYE = 0x02, // 접속 종료
	M_CALCREQ = 0x03, // 계산 요청
	M_CALCRES = 0x04, // 계산 결과
	M_LOGREQ = 0x05, // 로그 파일 요청
	M_LOGRES = 0x06 // 로그 파일 응답
};

typedef struct CalcInfo CalcInfo;

int Delim_PutMsg(CalcInfo *ci, uint8_t *outBuf, size_t bufSize, size_t hSize, FILE *channel);
int Delim_GetNextMsg(uint8_t *inBuf, size_t bufSize, FILE *channel);

size_t Text_Encode(char *tMsgs, uint8_t *outBuf, size_t bufSize);
size_t Text_Decode(char *tMsgs, uint8_t *inBuf, size_t bufSize);

int Length_PutMsg(CalcInfo *ci, uint8_t *outBuf, size_t bufSize, size_t hSize, FILE *channel);
int Length_GetNextMsg(uint8_t *inBuf, size_t bufSize, FILE *fp);

size_t Bin_Encode(uint8_t *outBuf, size_t bufSize, FILE *fp);
bool Bin_Decode(uint8_t *inBuf, uint8_t *tMsgs, size_t bufSize);

#endif /* PROTOCOL_H_ */
